package com.laolang.shop.common.data.mvc.trace;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @author khlbat
 * @version 1.0
 * @date 2020/11/1 20:46
 */
@Component
public class TraceComponent {

    private static final String AUTH_PREFIX = "/auth";
    private static final String ADMIN_PREFIX = "/admin";
    private static final String API_PREFIX = "/api";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public synchronized String getNextTraceId(String uri, LocalDateTime time) {
        StringBuilder sb = new StringBuilder();
        if (StrUtil.startWith(uri, AUTH_PREFIX)) {
            sb.append("1-");
        } else if (StrUtil.startWith(uri, ADMIN_PREFIX)) {
            sb.append("2-");
        } else if (StrUtil.startWith(uri, API_PREFIX)) {
            sb.append("3-");
        }
        sb.append(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH:mm:ss").format(time));
        sb.append("-");
        String key = "trace_id_" + DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(time);
        Object o = redisTemplate.opsForValue().get(key);
        if (null == o) {
            sb.append(1);
            redisTemplate.opsForValue().set(key, 2);
        } else {
            Integer id = Integer.parseInt(o.toString()) + 1;
            sb.append(id);
            redisTemplate.opsForValue().set(key, id);
        }
        redisTemplate.expire(key, 75, TimeUnit.SECONDS);
        return sb.toString();
    }
}
